package com.gmlive.common.sample.update

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.view.KeyEvent
import com.gmlive.common.sample.update.entity.AppUpdateEntity
import com.gmlive.common.appupdate.entity.PromptEntity
import com.gmlive.common.appupdate.entity.UpdateEntity
import com.gmlive.common.appupdate.proxy.IUpdatePrompter
import com.gmlive.common.appupdate.proxy.IUpdateProxy
import com.gmlive.common.appupdate.service.OnFileDownloadListener
import com.gmlive.common.ui.dialog.IkAlertDialog
import java.io.File
import java.lang.ref.WeakReference
import kotlin.math.roundToInt

class AppUpdatePrompter: IUpdatePrompter {

    private fun getPromptContent(entity: AppUpdateEntity): String {
        val version = "新版本：V${entity.versionName}(${AppUpdateUtils.formatApkSize(entity.size)})"
        return "$version\n" + entity.updateContent
    }

    override fun showPrompt(updateEntity: UpdateEntity, updateProxy: IUpdateProxy, promptEntity: PromptEntity) {
        if (updateEntity.isForce) {
            showForceUpdateDialog(updateEntity, updateProxy)
        } else {
            showNormalUpdateDialog(updateEntity, updateProxy)
        }
    }

    private fun showNormalUpdateDialog(entity: UpdateEntity, proxy: IUpdateProxy) {
        val updateContent = getPromptContent(entity as AppUpdateEntity)
        val appUpdateEntity = entity as AppUpdateEntity
        IkAlertDialog.Builder(proxy.context)
                .setTitle(appUpdateEntity.title)
                .setMessage(updateContent)
                .setPositiveButton(appUpdateEntity.positiveText) { _, _ ->
                    proxy.startDownload(entity, null)
                }
                .setNegativeButton(appUpdateEntity.negativeText) { _, _ ->
                    // 一旦忽略，相同版本不再提示
                    //UpdateUtils.saveIgnoreVersion(proxy.context, entity.versionName)
                }
                .show()
    }

    private fun showForceUpdateDialog(entity: UpdateEntity, proxy: IUpdateProxy) {
        val updateContent = getPromptContent(entity as AppUpdateEntity)
        val appUpdateEntity = entity as AppUpdateEntity
        IkAlertDialog.Builder(proxy.context)
                .setTitle(appUpdateEntity.title)
                .setMessage(updateContent)
                .setPositiveButton(appUpdateEntity.positiveText, false) { dialog, _ ->
                    proxy.startDownload(entity, ForceUpdateDownloadListener(dialog))
                }
                .setOnKeyListener(DialogInterface.OnKeyListener { dialog, keyCode, event ->
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        return@OnKeyListener true
                    }
                    false
                })
                .setCancelable(false)
                .show()
    }

    private class ForceUpdateDownloadListener(dialog: DialogInterface): OnFileDownloadListener {
        private val buttonRef = WeakReference((dialog as IkAlertDialog).getButton(DialogInterface.BUTTON_POSITIVE))

        override fun onStart() {
            buttonRef.get()?.text = "正在下载.."
        }

        @SuppressLint("SetTextI18n")
        override fun onProgress(progress: Float, total: Long) {
            //做一下判断，防止自回调过于频繁，造成更新通知栏进度过于频繁，而出现卡顿的问题。
            val rate = (progress * 100).roundToInt()
            buttonRef.get()?.text = "正在下载: $rate%"
        }

        override fun onError(throwable: Throwable?) {
            // ToastCompat.showToast("apk下载失败：${throwable?.message}")
        }

        /**
         * 返回值说明：
         * true：下载完成后自动跳转安装
         * false：不自动安装
         */
        override fun onCompleted(file: File?): Boolean {
            buttonRef.get()?.text = "点击安装"
            return true
        }

    }
}